#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

"""This module sets up the entire data API for Classifies.it."""

__author__ = 'alainv@google.com'

import simplejson

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import model


class ItemsHandler(webapp.RequestHandler):

  def _GetIdFromUri(self):
    """Return the ID from the current request URI, or None if no ID found."""
    parts = self.request.path.split('/')
    if len(parts) == 5 and parts[-1]:
      return parts[-1]
    return None

  def _GetItemModel(self, item_id):
    item = None
    try:
      item = model.Item.get_by_id(int(item_id))
    except db.BadArgumentError:
      pass
    except ValueError:
      pass
    return item

  def _GetItem(self, item_id):
    item = self._GetItemModel(item_id)
    if item:
      self.response.out.write(
          simplejson.dumps(self._ModelToItem(item)))
    else:
      self.response.set_status(404)
      self.response.out.write(
          'An item with the provided ID could not be found.')

  def _GetAll(self):
    max_results = 25
    if self.request.get('maxResults'):
      try:
        max_results = int(self.request['maxResults'])
      except ValueError:
        pass
    query = model.Item.all()
    query.filter('classified = ', False)
    data = query.fetch(max_results)
    result = {
        'items': [self._ModelToItem(x) for x in data]
    }
    self.response.out.write(
        simplejson.dumps(result))

  def get(self):
    item_id = self._GetIdFromUri()
    if item_id:
      self._GetItem(item_id)
    else:
      self._GetAll()

  def put(self):
    item_id = self._GetIdFromUri()
    if not item_id:
      self.response.set_status(400)
      return self.response.out.write(
          'No Item ID provided.')
    item = self._GetItemModel(item_id)
    if item:
      try:
        new_item = simplejson.loads(self.request.body)
        if new_item['tags']:
          item.tags = new_item['tags']
          item.classified = True
          item.put()
        self.response.set_status(204)
      except db.Error, e:
        self.response.set_status(500)
        self.response.out.write('Internal Server Error: %s' % e)
    else:
      self.response.set_status(404)
      self.response.out.write(
          'An item with the provided ID could not be found.')

  def post(self):
    for i in range(5):
      item = model.Item()
      item.title = 'title #' + str(i)
      item.data = 'data #' + str(i)
      item.summary = 'summary #' + str(i)
      item.url = 'url #' + str(i)
      item.classified = False
      item.tags = []
      item.put()


  @staticmethod
  def _ModelToItem(item):
    return {
        'title': item.title,
        'data': item.data,
        'summary': item.summary,
        'url': item.url,
        'tags': item.tags,
        'id': item.key().id()
    }


class TagsHandler(webapp.RequestHandler):
  def get(self):
    data = {
        'tags': [
            'jerky',
            'smarty',
            'stupid',
            'awesome',
            'boring',
            'meh'
        ]
    }
    self.response.out.write(
        simplejson.dumps(data))


application = webapp.WSGIApplication(
    [
        ('/resources/v1/items.*', ItemsHandler),
        ('/resources/v1/tags', TagsHandler)
    ],
    debug=True)


def main():
  run_wsgi_app(application)


if __name__ == "__main__":
  main()
